import UserApi from '../api/user';

export const user = {
    state:{
        user:{},
        userLoadStatus: 0,
        userUpdateStatus:0,
        userToken:'',
    },
    actions:{
        loadUser({commit,state},data){
            var localToken = window.localStorage.getItem('token');
            if(localToken){
                commit('setUserToken',localToken)
            }
            if(state.userToken !=='' || localToken){
                commit('setUserLoadStatus',1);
                UserApi.getUser().then(function (response) {
                    commit('setUser',response.data.data);
                    commit('setUserLoadStatus',2);
                }).catch(function () {
                    commit('setUser',{});
                    commit('setUserLoadStatus',3);
                })
            }
        },
        userLogout({commit},data){
            UserApi.logout().then(function (response) {
                commit('setUser',{});
                commit('setUserLoadStatus',0);
                commit('setUserToken','');
            }).catch(function (error) {
                console.log('注销操作失败')
            })
        },
        loginToken({commit},data){
            commit('setUserToken',data.token);
        },
        updateUser({commit,dispatch},data){
            commit('setUserUpdateStatus',1);
            UserApi.updateProfile(data).then(function (response) {
                commit('setUserUpdateStatus',2);
                dispatch('loadUser');
            }).catch(function (error) {
                commit('setUserUpdateStatus',3);
                var res = error.response;
                if(res){
                    this.$toast(res.data.message)
                }
            }.bind(this))
        },
        refreshUserToken({commit},data){
            window.localStorage.setItem('token',data.token);
            commit('setUserToken',data.token);
        },
    },
    mutations:{
        setUserLoadStatus:function (state,status) {
            state.userLoadStatus = status;
        },
        setUser:function (state,user) {
            state.user=user;
        },
        setUserToken:function (state,token) {
            state.userToken = token;
        },
        setUserUpdateStatus(state,status){
            state.userUpdateStatus=status;
        }
    },
    getters:{
        getUserLoadStatus(state){
            return function () {
                return state.userLoadStatus;
            }
        },
        getUser(state){
            return state.user;
        },
        getUserToken(state){
            return state.userToken;
        },
        getUserUpdateStatus(state){
            return state.userUpdateStatus;
        }
    }
};
